import { Component, Fragment } from 'react'; // 占位符
import store from './store/index';
import { Input, Button, List } from 'antd';
import 'antd/dist/antd.css';
import { initListAction, changeInputAction, addItemAction, delItemAction, getTodoList } from './store/actionCreator';

class NewTodoList extends Component {
    constructor(props) {
        super(props);
        this.state = store.getState();
        store.subscribe(this.storeChange.bind(this)); // store发生改变时，自动触发
    }
    render() {
        return (
            <Fragment>
                <div>
                    <Input value={this.state.value} style={{ width: '300px', margin: '10px' }} onChange={this.change.bind(this)} />
                    <Button type="primary" onClick={this.addItem.bind(this)}>
                        提交
                    </Button>
                    <List bordered dataSource={this.state.list} renderItem={(item, index) => <List.Item onClick={this.delItem.bind(this, index)}> {item} </List.Item>} style={{ width: '300px', margin: '10px' }} />
                </div>
            </Fragment>
        );
    }
    componentDidMount() {
        // 使用redux-thunk后，action可以返回函数，用于进行异步请求(axios)
        // const action = getTodoList();
        // store.dispatch(action);

        const action = {
            type: 'get_init_list',
        };
        store.dispatch(action); // action不仅会被reducer接收，还会被redux-saga接收
    }
    storeChange() {
        this.setState(store.getState());
    }
    change(e) {
        // const action = {
        //     type: 'change_input',
        //     value: e.target.value,
        // };
        const action = changeInputAction(e.target.value);
        store.dispatch(action);
    }
    addItem(e) {
        const action = addItemAction();
        store.dispatch(action);
    }
    delItem(index) {
        const action = delItemAction(index);
        store.dispatch(action);
    }
}

export default NewTodoList;
